{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "<table class=\"ee-notebook-buttons\" align=\"left\">\n",
        "    <td><a target=\"_blank\"  href=\"https://github.com/giswqs/earthengine-py-notebooks/tree/master/Algorithms/center_pivot_irrigation_detector.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /> View source on GitHub</a></td>\n",
        "    <td><a target=\"_blank\"  href=\"https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/Algorithms/center_pivot_irrigation_detector.ipynb\"><img width=26px src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png\" />Notebook Viewer</a></td>\n",
        "    <td><a target=\"_blank\"  href=\"https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/Algorithms/center_pivot_irrigation_detector.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /> Run in Google Colab</a></td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Install Earth Engine API and geemap\n",
        "Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geemap](https://geemap.org). The **geemap** Python package is built upon the [ipyleaflet](https://github.com/jupyter-widgets/ipyleaflet) and [folium](https://github.com/python-visualization/folium) packages and implements several methods for interacting with Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, and `Map.centerObject()`.\n",
        "The following script checks if the geemap package has been installed. If not, it will install geemap, which automatically installs its [dependencies](https://github.com/giswqs/geemap#dependencies), including earthengine-api, folium, and ipyleaflet."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "# Installs geemap package\n",
        "import subprocess\n",
        "\n",
        "try:\n",
        "    import geemap\n",
        "except ImportError:\n",
        "    print('Installing geemap ...')\n",
        "    subprocess.check_call([\"python\", '-m', 'pip', 'install', 'geemap'])"
      ],
      "outputs": [],
      "execution_count": null
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "import ee\n",
        "import geemap"
      ],
      "outputs": [],
      "execution_count": null
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Create an interactive map \n",
        "The default basemap is `Google Maps`. [Additional basemaps](https://github.com/giswqs/geemap/blob/master/geemap/basemaps.py) can be added using the `Map.add_basemap()` function. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "Map = geemap.Map(center=[40,-100], zoom=4)\n",
        "Map"
      ],
      "outputs": [],
      "execution_count": null
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Add Earth Engine Python script "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "# Add Earth Engine dataset\n",
        "# Center-pivot Irrigation Detector.\n",
        "#\n",
        "# Finds circles that are 500m in radius.\n",
        "Map.setCenter(-106.06, 37.71, 12)\n",
        "\n",
        "# A nice NDVI palette.\n",
        "palette = [\n",
        "  'FFFFFF', 'CE7E45', 'DF923D', 'F1B555', 'FCD163', '99B718',\n",
        "  '74A901', '66A000', '529400', '3E8601', '207401', '056201',\n",
        "  '004C00', '023B01', '012E01', '011D01', '011301']\n",
        "\n",
        "# Just display the image with the palette.\n",
        "image = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_034034_20170608')\n",
        "ndvi = image.normalizedDifference(['B5','B4'])\n",
        "\n",
        "Map.addLayer(ndvi, {'min': 0, 'max': 1, 'palette': palette}, 'Landsat NDVI')\n",
        "\n",
        "# Find the difference between convolution with circles and squares.\n",
        "# This difference, in theory, will be strongest at the center of\n",
        "# circles in the image. This region is filled with circular farms\n",
        "# with radii on the order of 500m.\n",
        "farmSize = 500  # Radius of a farm, in meters.\n",
        "circleKernel = ee.Kernel.circle(farmSize, 'meters')\n",
        "squareKernel = ee.Kernel.square(farmSize, 'meters')\n",
        "circles = ndvi.convolve(circleKernel)\n",
        "squares = ndvi.convolve(squareKernel)\n",
        "diff = circles.subtract(squares)\n",
        "\n",
        "# Scale by 100 and find the best fitting pixel in each neighborhood.\n",
        "diff = diff.abs().multiply(100).toByte()\n",
        "max = diff.focal_max(**{'radius': farmSize * 1.8, 'units': 'meters'})\n",
        "# If a pixel isn't the local max, set it to 0.\n",
        "local = diff.where(diff.neq(max), 0)\n",
        "thresh = local.gt(2)\n",
        "\n",
        "# Here, we highlight the maximum differences as \"Kernel Peaks\"\n",
        "# and draw them in red.\n",
        "peaks = thresh.focal_max(**{'kernel': circleKernel})\n",
        "Map.addLayer(peaks.updateMask(peaks), {'palette': 'FF3737'}, 'Kernel Peaks')\n",
        "\n",
        "# Detect the edges of the features.  Discard the edges with lower intensity.\n",
        "canny = ee.Algorithms.CannyEdgeDetector(ndvi, 0)\n",
        "canny = canny.gt(0.3)\n",
        "\n",
        "# Create a \"ring\" kernel from two circular kernels.\n",
        "inner = ee.Kernel.circle(farmSize - 20, 'meters', False, -1)\n",
        "outer = ee.Kernel.circle(farmSize + 20, 'meters', False, 1)\n",
        "ring = outer.add(inner, True)\n",
        "\n",
        "# Highlight the places where the feature edges best match the circle kernel.\n",
        "centers = canny.convolve(ring).gt(0.5).focal_max({'kernel': circleKernel})\n",
        "Map.addLayer(centers.updateMask(centers), {'palette': '4285FF'}, 'Ring centers')\n"
      ],
      "outputs": [],
      "execution_count": null
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Display Earth Engine data layers "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "Map.addLayerControl() # This line is not needed for ipyleaflet-based Map.\n",
        "Map"
      ],
      "outputs": [],
      "execution_count": null
    }
  ],
  "metadata": {
    "anaconda-cloud": {},
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.6.1"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 4
}